<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <NewPageFilter
      v-model:query="filterInfo.query.queryMap"
      :query-more-json="true"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
    >
    </NewPageFilter>
    <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
      <dialog-table
        ref="resourceTable"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :highlight-row="highlightRow"
        :row-key="rowKey"
        :checkedList="checkedRowList.map((item) => item.assetCapitalProjectId)"
        :reserve-selection="true"
        :check-box="checkBox"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-useAmount="scope">
          <el-form-item class="margin-bottom" @click.stop.native="">
            <div class="page-table-input-number-wrapper">
              <div class="page-table-input-number-left">
                <div class="page-table-input-number-item">
                  <el-input-number
                    v-model="scope.row.useAmount"
                    style="width: 100%"
                    controls-position="right"
                    :min="0"
                    :max="scope.row.amount - scope.row.usedAmount"
                    :precision="
                      $store.state.permission.systemConfig
                        .assets_price_precision
                        ? $store.state.permission.systemConfig
                            .assets_price_precision
                        : 0
                    "
                    :step="1"
                  />
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>
<script setup name="selectAsset">
import PageDialog from '../PageDialog/index'
import DialogTable from '../DialogTable/index'
import NewPageFilter from '../NewPageFilter/index'
import { getCustomizeSetting } from '@/api/customize'
import { getCapitalProjectCustomizeListPage } from '@/api/asset'
const emit = defineEmits()
const { proxy } = getCurrentInstance()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getCapitalProjectCustomizeListPage,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  showPrice: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  queryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  tableKey: {
    type: String,
    default:
      'AssetCapitalProjectQueryList-com.slip.spd.entity.vo.asset.settings.AssetCapitalProjectVO',
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
  checkedRowList: {
    type: Array,
    default: () => {
      return []
    },
  },
  saveEmpty: {
    type: Boolean,
    default: false,
  },
  qty: {
    type: Number,
  },
  assetId: {
    type: Number,
  },
  capitalProjectData: {
    type: Array,
    default: () => {
      return []
    },
  },
})
const sortString = ref('')
// 过滤相关配置
const filterInfo = reactive({
  query: {
    page: true,
    customizeUserVO: {},
    sortString: sortString.value,
    queryMap: {
      status: {
        queryType: 'IN',
        value: 2,
      },
    },
    queryParams: {
      // excludeNonAvailableMoney: true,
    },
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
})
let asset_project_type_valid = ref(proxy.$store.state.permission.systemConfig.asset_project_type_valid)
if(asset_project_type_valid.value) {
  filterInfo.query.queryParams['excludeNonAvailableMoney'] = true
}
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择资金项目',
  width: '70%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: !props.saveEmpty,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref([])

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

let obj = {
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'asset_capital_project_status',
    show: false,
    hidden: true,
  },

  usedAmount: {
    label: '已使用金额',
    value: 'usedAmount',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function save() {
  if (selectRow.value && selectRow.value.length) {
    let _selectRow = selectRow.value.filter((item) => !item.useAmount)
    if ((_selectRow && !_selectRow.length) || !asset_project_type_valid.value) {
      if (props.qty) {
        let name = []
        if (selectRow.value && selectRow.value.length) {
          tableInfo.value.data.forEach((row) => {
            selectRow.value.forEach((item) => {
              if (item.id === row.id) {
                let useAmount = 0
                useAmount = proxy.$fn.accMul(row.useAmount, props.qty)

                if (useAmount > proxy.$fn.Subtr(item.amount, item.usedAmount)) {
                  name.push(item.name)
                }
              }
            })
          })
        }
        if (name && name.length) {
          proxy.$alert(
            `使用金额超过资金项目【${String(
              name
            )}】可使用金额上限，请检查金额及建卡数量！`,
            '操作提示',
            {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
            }
          )
          return
        }
      }
      if (
        props.capitalProjectData &&
        props.capitalProjectData.length &&
        selectRow.value &&
        selectRow.value.length
      ) {
        let msg = ''
        tableInfo.value.data.forEach((row) => {
          selectRow.value.forEach((el) => {
            if (row.id === el.id) {
              props.capitalProjectData.forEach((item) => {
                if (props.assetId !== item.assetId) {
                  if (el.id === item.assetCapitalProjectId) {
                    let useAmountAll = 0
                    useAmountAll = proxy.$fn.accAdd(
                      useAmountAll,
                      item.useAmountAll
                    )
                    if (
                      proxy.$fn.accAdd(
                        useAmountAll,
                        proxy.$fn.accMul(row.useAmount, props.qty)
                      ) > proxy.$fn.Subtr(row.amount, row.usedAmount)
                    ) {
                      msg =
                        msg +
                        `资金项目【${el.name}】在当前的批量建卡操作中已填写使用金额【${useAmountAll}】元，填写的使用总金额超过可使用金额上限，请检查金额及建卡数量。<br>`
                    }
                  }
                }
              })
            }
          })
        })

        if (msg) {
          proxy.$alert(msg, '操作提示', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
          })
          return
        }
      }

      let data = []
      if (selectRow.value && selectRow.value.length) {
        tableInfo.value.data.forEach((item) => {
          selectRow.value.forEach((el) => {
            if (item.id === el.id) {
              data.push({ id: item.id, useAmount: item.useAmount })
            }
          })
        })
      }
      handleClose()
      emit('callback', selectRow.value, data)
    } else {
      proxy.$message.warning('请填写使用金额大于0！')
    }
  } else {
    handleClose()
    emit('callback', selectRow.value)
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      if (props.checkedRowList && props.checkedRowList.length) {
        tableInfo.value.data.forEach((item) => {
          if (props.query && props.query.assetId && props.query.assetId.value) {
            item['useAmount'] = proxy.$fn.Subtr(item.amount, item.usedAmount)
          }
          props.checkedRowList.forEach((el) => {
            if (
              el.assetCapitalProjectId === item.id &&
              el.useAmount !== undefined
            ) {
              item['useAmount'] = el.useAmount
            }
          })
        })
      } else {
        if (props.query && props.query.assetId && props.query.assetId.value) {
          tableInfo.value.data.forEach((item) => {
            item['useAmount'] = proxy.$fn.Subtr(item.amount, item.usedAmount)
          })
        }
      }
      break
    case 'tableClickRow':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.btList[1].disabled = !selectRow.value
      }
      break
    case 'tableCheck':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.btList[1].disabled = !selectRow.value
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function getCustomize() {
  let param = { tableKey: props.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let arr = [
        {
          label: '使用金额',
          value: 'useAmount',
          componentType: 'number',
          type: 'slot',
          formatter: proxy.$fn.TripartiteMethodAsset,
          show: true,
          hidden: !asset_project_type_valid.value,
          minWidth: '250px',
        },
      ]
      tableInfo.value.fieldList = arr.concat(tableInfo.value.fieldList)

      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })

      filterInfo.query.customizeUserVO = data
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
        ...props.query,
      }
      filterInfo.query.queryParams = {
        ...filterInfo.query.queryParams,
        ...props.queryParams,
      }
      tableInfo.value.api = props.api
      getList()
    }
  })
}
</script>
